package org.apache.commons.graph.model

import org.apache.commons.graph.DirectedGraph
import org.apache.commons.graph.Graph
import org.apache.commons.graph.bean.DefaultEdge

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

/**
 * A memory-based implementation of a mutable directed Graph.
 *
 * This class is NOT thread safe!
 *
 * @param <V> the Graph vertices type
 * @param <E> the Graph edges type
</E></V> */
class DirectedMutableGraph<V, E> : BaseMutableGraph<V, E>(), DirectedGraph<V, E> {
    private val inbound: MutableMap<V, MutableSet<V>> = HashMap()

    private val outbound: MutableMap<V, MutableSet<V>> = HashMap()

    /**
     * {@inheritDoc}
     */
    override fun decorateAddEdge(head: V, e: E, tail: V) {
        inbound[tail]!!.add(head)
        outbound[head]!!.add(tail)
    }

    /**
     * {@inheritDoc}
     */
    override fun decorateAddVertex(v: V) {
        inbound[v] = LinkedHashSet()
        outbound[v] = LinkedHashSet()
    }

    /**
     * {@inheritDoc}
     */
    override fun decorateRemoveEdge(e: E) {
        val vertices = getVertices(e)?:return
        inbound[vertices.tail]?.remove(vertices.head)
        outbound[vertices.head]?.remove(vertices.tail)
    }

    /**
     * {@inheritDoc}
     */
    override fun decorateRemoveVertex(v: V) {
        inbound.remove(v)
        outbound.remove(v)
    }

    /**
     * {@inheritDoc}
     */
    override fun getDegree(v: V): Int {
        return getInDegree(v) + getOutDegree(v)
    }

    /**
     * {@inheritDoc}
     */
    override fun getInbound(v: V): Iterable<V> {
        return inbound[v]?: emptyList()
    }

    /**
     * {@inheritDoc}
     */
    override fun getInDegree(v: V): Int {
        return inbound[v]?.size?:0
    }

    /**
     * {@inheritDoc}
     */
    override fun getOutbound(v: V): Iterable<V> {
        return outbound[v]?: emptyList()
    }

    /**
     * {@inheritDoc}
     */
    override fun getOutDegree(v: V): Int {
        return outbound[v]?.size?:0
    }

}
